import UserCenter from '@/util/user.js'
import $util from '@/util/util.js'
import permission from "@/util/permission.js" 
import {tool} from '@/util/tool.js'
//import {
//	encode
//} from '@/util/base64.js'
const $upimage = {
	//上传权限
	up(prame = {}, num = 9, callback = []){
	// #ifndef APP
	this.up_(prame, num, callback);
	return
	// #endif
	permission.request({id:'photoLibrary',name:'相册'},(res)=>{
	if(res){
	this.up_(prame, num, callback);
	}
	},'上传图片/照片需要请求您的相机权限哦，请您同意并开启！');
	},
	//上传
	up_(prame = {}, num, callback) { 
		console.log(JSON.stringify(prame))
		
		if (!prame.type || prame.type == 1) {
			uni.chooseImage({
				count: num, //默认9
				sizeType: prame.sizeType?prame.sizeType:['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: prame.sourceType?prame.sourceType:['album','camera'], //从相册选择
				success: function(res) {
					//console.log('xuanqu'+JSON.stringify(res))
					callback(res, false)
				},
				fail: function(err) {
					//console.log('xuanqushibai'+JSON.stringify(err))
					callback(false, err)
				}
			});
		}

		if (prame.type == 2) {
			uni.chooseVideo({
				sourceType: ['camera', 'album'],
				maxDuration:60,
				compressed:false, 
				success: function(res) {
				callback(res, false) 
				},
				fail:function(err){
				callback(false, err)	
				}
			});
		}
	},
	previewImage(paths, i = 0) {
		// 预览图片
		uni.previewImage({
			urls: paths,
			indicator: 'number',
			current: i,
			longPressActions: {
				itemList: ['保存原图'],
				success: function(data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index ) + '张图片');
					let index = data.tapIndex + 1;
					let ii = data.index;
					if(index == 1){
					uni.saveImageToPhotosAlbum({
								filePath: paths[ii].split("?x-oss-process")[0],
								success: function () {
									console.log('save success');
									$util.toast('保存成功')
								}
							});
					}
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});
	},
	//直接传oss
	oss_upfield(prame = {
		path: "",
		ossdata: [],
		calltext: ""
	}, callback = [],callback_video= false) {
		//path不能为空ossdata=鉴权信息，calltext，回调信息，用于oss像服务器发送回调
		//calltext = "type=lifetime&model=lifetime_imgs&lifeid="+lifeid+"&index="+(i+1),要传递的值
		let formData = prame.ossdata;
		formData.key = formData.key_diy + this.randomString(18, prame.path);
		let calltext = prame.calltext + "&path=" + formData.key + "&userid=" + UserCenter.getUserInfo().id;
		formData.callback = this.getcallback(calltext);
		//console.log('suoyoude '+JSON.stringify(formData));
		console.log('formData.host '+formData.host);
		//return  
		let that = this;
		let uploadTask = uni.uploadFile({
			url: formData.host, //开发者服务器 url
			filePath: prame.path, //要上传文件资源的路径
			name: 'file', //必须填file  
			formData: formData,
			success: function(res) {
				console.log(JSON.stringify(res));
				if (res.statusCode != 200 && res.statusCode != 203) {
					$util.toast('开始备用上传...');
					that.upfield(prame, callback);
					return
				}
				//if(res.statusCode == 203){
				//that.deal203(prame, callback);//把路径传过去
				//}else{
				if(callback){
				callback(res,prame)
				}	
				//}
			},
			fail: function(err) {
				console.log(JSON.stringify(err));
			},
		})
		uploadTask.onProgressUpdate((res_video) => {
		// 测试条件，取消上传任务。
		//if (res.progress > 50) {
		//	uploadTask.abort();
		//}
		if(callback_video){
		callback_video(res_video)
		}
		});
		
	},
	//先传服务器备案
	upfield(prame = {
		path: "",
		field: ''
	}, callback = []) {
		//path不能为空
		uni.uploadFile({
			url: tool.apiurl+'upload/upimg',
			filePath: prame.path,
			name: 'file',
			formData: {
				'userid': UserCenter.getUserInfo().id,
				'filekey': this.randomString(),
				'savepath': prame.field ? prame.field : '',
				'type': prame.type ? prame.type : 'lifetime',
				'lifeid': prame.lifeid ? prame.lifeid : "",
				'prame':prame.prame?JSON.stringify(prame.prame):''
			},
			timeout: 60000,
			success: (uploadFileRes) => {
				//console.log('y88888888888'+JSON.stringify(uploadFileRes));
				callback(uploadFileRes, prame)
			}
		});
	},
	
	//203的处理方案
	deal203(prame= {},callback={}){
	$util.ajax({
		url: 'Upload/deal203',
		path:"/"+prame.ossdata.key,
		type: prame.type ? prame.type : 'lifetime',
		lifeid: prame.lifeid ? prame.lifeid : ""
	}, (res, err) => {
		if (res.code == 1) {
			callback(res.data);
		} else {
			$util.toast('获取上传参数失败，请重试或联系客服')
		}
	})
	},
	//oss授权
	osspost(path, callback = []) {
		$util.ajax({
			url: 'Upload/gettoken',
			path: path
		}, (res, err) => {
			if (res.code == 1) {
				callback(res.data);
			} else {
				$util.toast('获取上传参数失败，请重试或联系客服')
			}
		})
	},
	//oss base64位回调
	getcallback(calltext = "type=null&model=null") {
		console.log(calltext)
		const arr = {
			"callbackUrl": tool.apiurl+"Upload/getcallback_url",
			"callbackBody": JSON.stringify([calltext]),
			"callbackBodyType": "application/json"
		}
		//return encode(JSON.stringify(arr));
	},
	//file name - rand
	randomString(len, filename = "") {
		len = len || 32;
		/****Confusing characters are removed by default :::oOLl,9gq,Vv,Uu,I1****/
		var $chars = 'abcdefhijkmnprstwxyz2345678';
		var maxPos = $chars.length;
		var pwd = '';
		for (var i = 0; i < len; i++) {
			pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
		}
		var d = new Date();
		var s = d.getTime();
		if (parseInt(s) >= 1) {
			pwd = pwd + parseInt(s);
		}
		if (filename != "") {
			let pos = filename.lastIndexOf('.');
			if (pos != -1) {
				return pwd + filename.substring(pos);
			}else{
				return pwd + '.jpg';
			}
		}
		return pwd;
	},
	//获取图片的储存大小
	getImageInfo(path, callback = []) {
		// #ifdef MP-WEIXIN
		wx.getFileSystemManager().getFileInfo({
			filePath: path,
			success: (res) => {
				console.log(JSON.stringify(res))
				callback(res.size);
			},
			fail: (err) => {
				callback(0);
			}
		})
		// #endif

		// #ifndef MP-WEIXIN
		uni.getFileInfo({
			filePath: path,
			success: (res) => {
				//console.log(JSON.stringify(res))
				callback(res.size);
			},
			fail: (err) => {
				callback(0);
			}
		})
		// #endif

	},
	//获取图片的尺寸大小
	getSizeInfo(path, callback = []) {
		uni.getImageInfo({
			src: path,
			success: function(image) {
				//console.log(JSON.stringify(image))
				callback(image);
			},
			fail: function(err) {
				callback({
					"width": 0,
					"height": 0
				});
			}
		});
	},
	//获取图片大小决定是否压缩
	compressImage(path, callback = []) {
		this.getImageInfo(path, (size) => {
			if (size <= 1.2 * 1024 * 1024) { 
				callback(path);
			} else {
				//检测宽高
				this.getSizeInfo(path, (w_size) => {
					let width = 'auto';
					let quality = 80;
					if (w_size.width >= 2000) {
						width = '2000px'
					}
			this.compressImage_1({path:path,width:width,quality:quality},(yspath)=>{
			callback(yspath);
			})
				})
			}
		});
	},
	compressImage_1(prame=[],callback=''){
	// #ifdef H5
	callback(prame.path);
	return 
	// #endif

	//prame.path不能为空
	uni.compressImage({ 
		src: prame.path,
		quality: prame.quality?prame.quality:80,
		// #ifdef APP
		width: prame.width?prame.width+'px':'auto',
		height: prame.height?prame.height+'px':'auto',
		// #endif
		// #ifdef MP-WEIXIN
		compressedWidth: prame.width?prame.width:'',
		// #endif
		success: (res) => {
			callback(res.tempFilePath);
		},
		fail: (err) => {
			callback(prame.path);
		}
	})	
	},
	compressVideo(path,prame = {},callback){

	//获取视频信息
	uni.getVideoInfo({
	  src: path,
	  success (res) {
		 res.width = parseInt(res.width)
		 res.height = parseInt(res.height)
		//计算最长边
		let max = res.height;
		if(res.width > res.height){
		max = res.width
		}
		max = parseInt(max);
		//计算压缩后的比例
		let resolution = 1;
		if(max >1080){
		resolution = 1-((max-1080)/max);
		}
		//启动条件压缩
		uni.compressVideo({
		  src: path,
		  	quality:prame.quality?prame.quality:'high',
			bitrate:5000,
			fps:26,
			resolution:resolution,
		  success (res_){
		    console.log(JSON.stringify(res_))
			callback(res_.tempFilePath)
		  },
		  fail(res){
		  callback(path)
		  }
		})
		/*条件压缩结束*/
		
	  },
	  fail(res){
	  callback(path)
	  }
	})
	},
	down(link,callback){
	// #ifdef MP
	uni.downloadFile({
		url: link, //仅为示例，并非真实的资源
		timeout:30*1000,
		success: (res) => {
			if (res.statusCode === 200) {
				callback(res)
				return
			}
			callback(false)
		}
	});
	return
	// #endif
	permission.request({id:'writestorage',name:'手机储存'},(res)=>{
	if(res){
		
	uni.downloadFile({
		url: link, //仅为示例，并非真实的资源
		timeout:30*1000,
		success: (res) => {
			if (res.statusCode === 200) {
				callback(res)
				return
			}
			callback(false)
		}
	});
	
	}
	});
		
	}
	
}
export default $upimage;
